/**
 * 
 */
package com.zte.claa.inficombo.csa.app.util;

import java.lang.reflect.Field;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.util.StringUtils;

/**
 * 代码安全辅助类
 * @author zhanghao
 *
 */
public class CodeSafe {

	private static final Logger logger = LoggerFactory.getLogger(CodeSafe.class.getName());
	
	private final static String SQL_INJECT_REGEX = "(?i)'|%|--| and | or | not | use | insert | delete | update | select | count | group | union | create | drop | truncate | alter | grant | execute | exec | xp_cmdshell | call | declare | source | sql "; 
	
	//过滤xss字符
	public static String xssFilter(String str){
		if (StringUtils.isEmpty(str)){
			return str;
		}
        String sanitized = str;  
        sanitized = sanitized.replaceAll("<", "&lt;").replaceAll(">", "&gt;");  
        sanitized = sanitized.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;");  
        sanitized = sanitized.replaceAll("'", "&#39;");  
        sanitized = sanitized.replaceAll("eval\\((.*)\\)", "");  
        sanitized = sanitized.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");  
        return sanitized; 
	}
	
	//过滤指定对象中所有的字符串
	public static void xssFilterObj(Object obj) {
		try {
			Class<?> cls = obj.getClass();
			Field[] fs = cls.getDeclaredFields();
			for (int i = 0; i < fs.length; i++) {
				Field f = fs[i];
				f.setAccessible(true); // 设置属性是可以访问的
				if ((f.getModifiers() & 16) == 16) {
					continue;
				}
				String type = f.getType().toString();// 得到此属性的类型
				if (!type.endsWith("String")) {
					continue;
				}
				String val = (String)f.get(obj);
				f.set(obj, xssFilter(val));
			}
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
	}
	
	//过滤SQL注入字符
	public static String sqlInjectFilter(String sql){
		if (StringUtils.isEmpty(sql)){
			return sql;
		}
        return sql.replaceAll(SQL_INJECT_REGEX, "");
	}
	
}
